package com.wy.demo;

import com.wy.demo.service.VideoService;
import com.wy.demo.service.impl.VideoServiceImpl;
import org.junit.Test;

import java.io.File;
import java.util.Random;

public class RunService {
    private static final VideoService videoService = new VideoServiceImpl();
    private static final String RESOURCE_MP3_PATH = "src/main/resources/mp3/"; // MP3资源目录

    public static void main(String[] args) {
        String inputPath = "C:\\Users\\wy\\Desktop\\222\\d80d3488a05798e02ec34c669d9eac1f.mp4";
        String outputPath = generateOutputPath(inputPath);
        String randomMusicPath = getRandomMusicPath(RESOURCE_MP3_PATH);
        boolean run = videoService.run(inputPath, outputPath, randomMusicPath);
        if (run) {
            System.out.println("视频处理成功！");
        } else {
            System.err.println("视频处理失败！");
        }
    }

    @Test
    public void testRun2() {
        File file = new File("C:\\Users\\wy\\Desktop\\222\\555");
        String[] list = file.list();
        for (String inputPath : list) {
            String outputPath = generateOutputPath(inputPath);
            String randomMusicPath = getRandomMusicPath(RESOURCE_MP3_PATH);
            boolean run = videoService.run(inputPath, outputPath, randomMusicPath);
            if (run) {
                System.out.println(inputPath + "视频处理成功！");
            } else {
                System.err.println(inputPath +"视频处理失败！");
            }
        }
    }

    /**
     * 生成输出文件路径
     *
     * @param inputPath 输入文件路径
     * @return 输出文件路径
     */
    private static String generateOutputPath(String inputPath) {
        File inputFile = new File(inputPath);
        String parentPath = inputFile.getParent();
        String fileName = inputFile.getName();

        // 在文件名和扩展名之间插入"_handle"
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            String nameWithoutExt = fileName.substring(0, dotIndex);
            String extension = fileName.substring(dotIndex);
            return new File(parentPath, nameWithoutExt + "_handle" + extension).getAbsolutePath();
        } else {
            return new File(parentPath, fileName + "_handle").getAbsolutePath();
        }
    }

    private static String getRandomMusicPath(String musicPath) {
        File mp3Dir = new File(musicPath);
        if (!mp3Dir.exists() || !mp3Dir.isDirectory()) {
            System.err.println("MP3资源目录不存在: " + RESOURCE_MP3_PATH);
            return null;
        }

        File[] mp3Files = mp3Dir.listFiles((dir, name) -> name.toLowerCase().endsWith(".mp3"));
        if (mp3Files == null || mp3Files.length == 0) {
            System.err.println("MP3资源目录中没有MP3文件");
            return null;
        }

        File selectedFile = mp3Files[new Random().nextInt(mp3Files.length)];
        System.out.println("随机选择音乐文件：" + selectedFile.getName());
        return selectedFile.getAbsolutePath();
    }
}
